﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Data.Services.Client;
using System.Threading;
using System.ServiceModel;

namespace Buggy
{
	public partial class MainPage : UserControl
	{
		private int? selected_category_id = null;
		private int? selected_bug_id = null;
		private int? selected_bugComment_id = null;
		
		private string LoginedUser = null;
		private string LoginingUser = null;

        private readonly BuggyManager buggyManager = new BuggyManager();

		public MainPage()
		{
			InitializeComponent();
			Init();
		}

		void Init()
		{
            buggyManager.LoadCategories(UI_categories_update);

            this.tv_categories.SelectedItemChanged += new RoutedPropertyChangedEventHandler<object>(tv_categories_SelectedItemChanged);

            lb_bugs.ItemsSource = buggyManager.bugs;
			this.lb_bugs.SelectionChanged += new SelectionChangedEventHandler(lb_bugs_SelectionChanged);

            lb_bugComments.ItemsSource = buggyManager.bugComments;
			this.lb_bugComments.SelectionChanged += new SelectionChangedEventHandler(lb_bugComments_SelectionChanged);			
			
			button_addComment.Click += new RoutedEventHandler(button_addComment_Click);
			button_changeComment.Click += new RoutedEventHandler(button_changeComment_Click);
			button_changeBugName.Click += new RoutedEventHandler(button_changeBugName_Click);
			button_changeBugDesc.Click += new RoutedEventHandler(button_changeBugDesc_Click);

			Button_DoLogin.Click += new RoutedEventHandler(Button_DoLogin_Click);
			Button_DoLogout.Click += new RoutedEventHandler(Button_DoLogout_Click);
			
            button_users.Click += (object obj, RoutedEventArgs e) => { contextmenu_users.IsOpen = true; };
			
			Button_Add_Bug.Click += new RoutedEventHandler(Button_Add_Bug_Click);
			
            //debug
			TextBox_Login.Text = "Joe";
			TextBox_Password.Text = "black";					
		}

        void Button_Add_Bug_Click(object sender, RoutedEventArgs e)
		{
            if ((selected_category_id != null) && (LoginedUser != null))
			{
                AddBug ab = new AddBug();
                ab.Show();
                ab.Closed += (object close_sender, EventArgs close_e) => 
                {
                    if ((ab.DialogResult.HasValue) && (ab.DialogResult.Value))
                        buggyManager.CreateBug(selected_category_id.Value, ab.Bug_name, ab.Bug_desc, (object obj) =>
                        {
                            if ((bool)obj == false)
                                MessageBox.Show("Error while creating bug");
                            else
                            {
                                if (selected_category_id != null)
                                    ChangeCategory(selected_category_id.Value);
                            }
                        });                        
                };
            }
		}

		public static Uri GetAbsoluteUri(string relativePath)
		{
			string fullpath = App.Current.Host.Source.OriginalString;
			string slpath = App.Current.Host.Source.LocalPath;
			string hostpath = fullpath.Remove(fullpath.IndexOf(slpath));
			//hostpath = hostpath.Replace("localhost", "127.0.0.1");
			return new Uri(hostpath + relativePath, UriKind.Absolute);
		}

		void Button_DoLogin_Click(object sender, RoutedEventArgs e)
		{
			LoginingUser = TextBox_Login.Text;
            buggyManager.Login(LoginingUser, TextBox_Password.Text, (object obj) =>
            {
                BuggyService.LoginStatusEnum loginresult = (BuggyService.LoginStatusEnum)obj;
                if (loginresult != BuggyService.LoginStatusEnum.OK)
                    MessageBox.Show("Error while making login");
                else
                {
                    TextBox_Login.Visibility = System.Windows.Visibility.Collapsed;
                    TextBox_Password.Visibility = System.Windows.Visibility.Collapsed;
                    TextBox_Password.Text = string.Empty;
                    Button_DoLogin.Visibility = System.Windows.Visibility.Collapsed;

                    LoginedUser = LoginingUser;
                    TextBlock_LoginCurrent.Text = LoginedUser;
                    TextBlock_LoginCurrent.Visibility = System.Windows.Visibility.Visible;
                    Button_DoLogout.Visibility = System.Windows.Visibility.Visible;                    
                }
            });			
		}

		void Button_DoLogout_Click(object sender, RoutedEventArgs e)
		{
			buggyManager.Logout((object obj) => 
            {
                BuggyService.LoginStatusEnum logoutresult = (BuggyService.LoginStatusEnum)obj;
                if (logoutresult != BuggyService.LoginStatusEnum.OK)
                    MessageBox.Show("Error while making logout");
                else
                {
                    LoginedUser = null;
                    TextBlock_LoginCurrent.Text = LoginedUser;
                    TextBlock_LoginCurrent.Visibility = System.Windows.Visibility.Collapsed;
                    Button_DoLogout.Visibility = System.Windows.Visibility.Collapsed;

                    TextBox_Login.Visibility = System.Windows.Visibility.Visible;
                    TextBox_Password.Visibility = System.Windows.Visibility.Visible;
                    Button_DoLogin.Visibility = System.Windows.Visibility.Visible;
                }
            });
		}
		
		void button_changeBugName_Click(object sender, RoutedEventArgs e)
		{
			if (selected_bug_id != null)
			{
                buggyManager.ChangeBugName((BuggyDataService.Bugs)lb_bugs.SelectedItem, 
                    textbox_bugName.Text, null);				
			}
		}

		void button_changeBugDesc_Click(object sender, RoutedEventArgs e)
		{
			if (selected_bug_id != null)
			{
                buggyManager.ChangeBugDescription((BuggyDataService.Bugs)lb_bugs.SelectedItem,
                    textbox_bugDesc.Text, null);				
			}
		}

		void button_changeComment_Click(object sender, RoutedEventArgs e)
		{
			if ((selected_bug_id != null) && (selected_bugComment_id != null))
			{
                buggyManager.ChangeBugComment((BuggyDataService.BugComments)lb_bugComments.SelectedItem,
                    textbox_newAndChangeComment.Text, null);
			}
		}

		void button_addComment_Click(object sender, RoutedEventArgs e)
		{
			if (selected_bug_id != null)
			{
                buggyManager.AddBugComment(selected_bug_id.Value, textbox_newAndChangeComment.Text,
                    (object obj) => {
                        textbox_newAndChangeComment.Text = "";
                        lb_bugs_SelectionChanged(lb_bugs, null);
                    });
			}
		}

		void lb_bugComments_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			var selectedItem = (sender as ListBox).SelectedItem;
			if ((selectedItem != null) && (selectedItem is BuggyDataService.BugComments))
			{
				var bc = (BuggyDataService.BugComments)selectedItem;
				int bugComment_id = bc.id;
				selected_bugComment_id = bugComment_id;
				textbox_newAndChangeComment.Text = bc.content;
			}
			else selected_bugComment_id = null;
		}

		void lb_bugs_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			var selectedItem = (sender as ListBox).SelectedItem;
			if ((selectedItem != null) && (selectedItem is BuggyDataService.Bugs))
			{
				textbox_newAndChangeComment.Text = "";
				var bug = (BuggyDataService.Bugs)selectedItem;
				textbox_bugName.Text = bug.name;
				textbox_bugDesc.Text = bug.description;
				selected_bug_id = bug.id;

				buggyManager.LoadBugComments(bug.id, null);
				
                Update_related_user_by_bug(bug.id);
			}
			else 
                selected_bug_id = null;
		}

        void Update_related_user_by_bug(int bugid)
        {
            buggyManager.GetRelatedUsersByBug(bugid, (object obj) =>
            {
                BuggyService.GetRelatedUsersByBugCompletedEventArgs e = 
                    (BuggyService.GetRelatedUsersByBugCompletedEventArgs)obj;
                if (e.Error != null)
                    MessageBox.Show("Error while getting users related to bug");
                else
                {
                    textbox_bugUsers.Text = "";
                    contextmenu_users.ItemsSource = e.Result;
                    foreach (BuggyService.UserInfo uinfo in e.Result)
                        if (uinfo.isRelatedToCurrentBug)
                            textbox_bugUsers.Text += uinfo.userLogin + "; ";
                }
            });
        }

		void tv_categories_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
		{
			var category = (sender as TreeView).SelectedItem;
			if (category != null)
			{
				int categoryId = (int)(category as TreeViewItem).Tag;
				selected_category_id = categoryId;
				ChangeCategory(categoryId);
			}
			else selected_category_id = null;
		}

		void ChangeCategory(int categoryId)
		{
			textbox_newAndChangeComment.Text = "";
			textbox_bugName.Text = "";
			textbox_bugDesc.Text = "";
			textbox_bugUsers.Text = "";

            buggyManager.LoadBugs(categoryId, null);			
		}

		void UI_categories_update(object obj)
		{
            DataServiceCollection<BuggyDataService.Categories> categories = 
                (DataServiceCollection<BuggyDataService.Categories>)obj;
			tv_categories.Items.Clear();
			foreach (BuggyDataService.Categories cat in categories)
			{
				TreeViewItem tvi_new = new TreeViewItem();				
				tvi_new.IsExpanded = true;
				tvi_new.Header = cat.name;
				tvi_new.Tag = cat.id;
				if (cat.parentId != null)
				{
					foreach (TreeViewItem tvi in tv_categories.Items)
					{
						if ((int)tvi.Tag == cat.parentId.Value)
						{
							tvi.Items.Add(tvi_new);
							break;
						}
					}
				}
				else tv_categories.Items.Add(tvi_new);
			}
		}

        private void button_user_add_Click(object sender, RoutedEventArgs e)
        {
            string username = (string)(sender as System.Windows.Controls.Button).Tag;
            if (selected_bug_id != null)
            {
                buggyManager.AddUserToBug(username, selected_bug_id.Value, (object obj) =>
                {
                    //System.ComponentModel.AsyncCompletedEventArgs e_async = (System.ComponentModel.AsyncCompletedEventArgs)obj;
                    Update_related_user_by_bug(selected_bug_id.Value);
                });
            }
        }

        private void button_user_remove_Click(object sender, RoutedEventArgs e)
        {
            string username = (string)(sender as System.Windows.Controls.Button).Tag;
            if (selected_bug_id != null)
            {
                buggyManager.RemoveUserFromBug(username, selected_bug_id.Value, (object obj) =>
                {
                    //System.ComponentModel.AsyncCompletedEventArgs e_async = (System.ComponentModel.AsyncCompletedEventArgs)obj;
                    Update_related_user_by_bug(selected_bug_id.Value);
                });
            }
        }
	}
}
